<template>
    <el-card>
        <el-form :inline="true" class="form">
            <el-form-item label="职位搜索">
                <el-input placeholder="请输入职位名称" v-model="keyword"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="search">搜索</el-button>
                <el-button type="primary" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card style="margin: 10px 0;">
        <el-button @click="addRole" type="primary" icon="Plus">添加职位</el-button>
        <el-table border style="margin: 10px 0;" :data="allRole">
            <el-table-column type="index" align="center" label="#" />
            <el-table-column label="ID" prop="id" />
            <el-table-column label="角色名称" prop="roleName" show-overflow-tooltip />
            <el-table-column label="创建时间" prop="createTime" show-overflow-tooltip />
            <el-table-column label="更新时间" prop="updateTime" show-overflow-tooltip />
            <el-table-column label="操作" width="280px;">
                <template #default="scope">
                    <el-button type="primary" size="small" icon="User"
                        @click="setPermission(scope.row)">分配权限</el-button>
                    <el-button type="primary" size="small" icon="Edit" @click="updateRole(scope.row)">编辑</el-button>
                    <el-popconfirm :title="`确定要删除${scope.row.roleName}吗？`" width="260px" @confirm="deleteRole(scope.row.id)">
                        <template #reference>
                            <el-button type="primary" size="small" icon="Delete">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination @current-change="getHasRole" @size-change="handleSizeChange" v-model:current-page="pageNo"
            v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]" :small="false" :disabled="false"
            :background="true" layout="prev, pager, next, jumper, ->, sizes,total" :total="total" />
    </el-card>
    <el-dialog v-model="show" :title="roleParams.id ? '修改职位' : '添加职位'">
        <el-form label-width="80px" :rules="rules" :model="roleParams" ref="formRef">
            <el-form-item label="角色名称" prop="roleName">
                <el-input placeholder="请输入角色名称" v-model="roleParams.roleName"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="show = false">取消</el-button>
                <el-button type="primary" @click="save">确定</el-button>
            </span>
        </template>
    </el-dialog>
    <!--抽屉组件：分配权限-->
    <el-drawer v-model="drawer">
        <template #header>
            <h4>分配菜单与按钮的权限</h4>
        </template>
        <template #default>
            <el-tree ref="treeRef" :data="menuArr" show-checkbox node-key="id" :props="defaultProps" default-expand-all
                :default-checked-keys="selectIdArr" />
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="drawer = false">取消</el-button>
                <el-button type="primary" @click="handler">确定</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script setup lang="ts">
import { reqAddOrUpdateRole, reqAllMenuList, reqAllRoleList, reqRemoveRole, reqSetPermisstion } from '@/api/acl/role';
import type { MenuList, Records, RoleData, RoleResponseData } from '@/api/acl/role/type';
import { ElMessage } from 'element-plus';
import { nextTick, onMounted, reactive, ref } from 'vue';

let pageNo = ref(1)
let pageSize = ref(5)
let total = ref(0)
let keyword = ref('')
//存储已有的职位
let allRole = ref<Records>([])
let show = ref(false)
let roleParams = reactive<RoleData>({
    roleName: ''
})
let formRef = ref()
let drawer = ref(false)
let menuArr = ref<MenuList>([])
let defaultProps = {
    children: 'children',
    label: 'name'
}
//准备一个数组：用于存储已选中的权限ID（最后一级就行，即按钮节点。因为最后一级勾选了，父节点就会自动勾选）
let selectIdArr = ref<number[]>([])
let treeRef = ref()
//组件挂载完毕
onMounted(() => {
    getHasRole()
})

const getHasRole = async (pager = 1) => {
    pageNo.value = pager
    let result: RoleResponseData = await reqAllRoleList(pageNo.value, pageSize.value, keyword.value)
    if (result.code === 200) {
        total.value = result.data.total
        allRole.value = result.data.records
    } else {
        ElMessage.error(result.message)
    }
}

const handleSizeChange = () => {
    getHasRole()
}

const search = () => {
    getHasRole()
}
const reset = () => {
    keyword.value = ''
    getHasRole()
}

const addRole = () => {
    show.value = true
    //清空数据
    Object.assign(roleParams, {
        id: 0,
        roleName: ''
    })
    //清空校验规则的错误提示信息
    nextTick(() => {
        formRef.value.clearValidate()
    })
}
const updateRole = (row: RoleData) => {
    show.value = true
    Object.assign(roleParams, row)
    //清空校验规则的错误提示信息
    nextTick(() => {
        formRef.value.clearValidate()
    })
}

const validatorRoleName = (_rule: any, value: any, callback: any) => {
    if (value.trim() === '') {
        callback(new Error('请输入角色名称'))
    } else {
        callback()
    }
}
const rules = reactive({
    roleName: [
        { required: true, trigger: 'blur', validator: validatorRoleName }
    ]
})
const save = async () => {
    //表单校验结果
    await formRef.value.validate()
    //添加或更新角色
    let result = await reqAddOrUpdateRole(roleParams)
    if (result.code === 200) {
        ElMessage.success(result.message)
        getHasRole()
        show.value = false
    } else {
        ElMessage.error(result.message)
    }

}

const setPermission = (row: RoleData) => {
    drawer.value = true
    Object.assign(roleParams, row)
    reqAllMenuList(roleParams.id as number).then(res => {
        if (res.code === 200) {
            menuArr.value = res.data
            selectIdArr.value = filterSelectArr(menuArr.value, [])
        }
    })
}

const filterSelectArr = (allData: MenuList, initArr: any) => {
    allData.forEach(item => {
        if (item.children && item.children.length > 0) {
            filterSelectArr(item.children, initArr)
        } else {
            if (item.select) {
                initArr.push(item.id)
            }
        }
    })
    return initArr
}
//抽屉确定按钮的回调
const handler = () => {
    const roleId = roleParams.id as number
    let arr = treeRef.value.getCheckedKeys()
    let arr1 = treeRef.value.getHalfCheckedKeys()
    selectIdArr.value = [...arr, ...arr1]
    reqSetPermisstion(roleId, selectIdArr.value).then(res => {
        if (res.code === 200) {
            drawer.value = false
            ElMessage.success("分配权限成功")
            //刷新页面，获取最新的权限角色数据
            window.location.reload()
        }
    })

}

const deleteRole = (id: number) => {
    reqRemoveRole(id).then(res => {
        if (res.code === 200) {
            ElMessage.success('删除成功')
            getHasRole(allRole.value.length > 1 ? pageNo.value : pageNo.value - 1)
        } else {
            ElMessage.error(res.message)
        }
    })
}
</script>

<style scoped>
.form {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 50px;
}
</style>